﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

namespace Framework.Constructor.Formularios
{
    public partial class frmConnectionStringBuilder : Form
    {
        protected String connectionString;
        protected String name;
        protected String providerName;
        protected Boolean testOk;

        public frmConnectionStringBuilder()
        {
            InitializeComponent();
            this.txt_TextChanged(this, null);
            this.HabilitarControles();
        }

        public ConnectionStringSettings Obtener()
        {
            ConnectionStringSettings resultado = null;
            DialogResult dResult = this.ShowDialog();
            if (dResult == DialogResult.OK)
            {
                resultado = new ConnectionStringSettings();
                resultado.ConnectionString = this.connectionString;
                resultado.Name = this.name;
                resultado.ProviderName = this.providerName;
            }
            return resultado;
        }

        private void txt_TextChanged(object sender, EventArgs e)
        {
            this.testOk = false;
            this.connectionString = txtConexion.Text;
            this.name = txtNombre.Text;
            this.providerName = txtProvider.Text;
            this.HabilitarControles();
        }

        private void HabilitarControles()
        {
            this.HabilitarBtnTest();
            this.HabilitarBtnGuardar();
            this.HabilitarBtnCancelar();
        }

        private void HabilitarBtnTest()
        {
            this.btnTestConnection.Enabled = txtConexion.Text != String.Empty && txtNombre.Text != String.Empty && txtProvider.Text != String.Empty;
        }

        private void HabilitarBtnGuardar()
        {
            this.btnGuardar.Enabled = this.testOk;
        }

        private void HabilitarBtnCancelar()
        {
            this.btnCancelar.Enabled = true;
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            btnTestConnection.Enabled = false;
            btnCancelar.Enabled = false;
            SqlConnection sqlConn;
            try
            {
                sqlConn = new SqlConnection(this.connectionString);
                sqlConn.Open();
                this.testOk = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.HabilitarControles();
        }

    }
}
